package pers.lance.xml.parse;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import pers.lance.xml.db.bean.Student;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Lance Li
 * @date 7/10/2018 6:46 PM
 * @desc
 */
public class StudentHandler extends DefaultHandler {

    String tag = null;
    Student student = null;
    List<Student> students = null;

    @Override
    public void startDocument() throws SAXException {

    }

    @Override
    public void endDocument() throws SAXException {
    }

    @Override
    public void startElement(String uri, String localName,
                             String qName, Attributes attributes) {
        tag = qName;
        if (tag.equals("students")) {
            students = new ArrayList<Student>();
        }
        if (tag.equals("student")) {
            student = new Student();
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        tag = null;
        if (qName.equals("student")) {
            students.add(student);
        }
    }

    @Override
    public void characters(char ch[], int start, int length)
            throws SAXException {
        String value = new String(ch, start, length);
        if (tag != null) {
            if (tag.equals("id") && !value.equals("")) {
                student.setId(Integer.parseInt(value));
            } else if (tag.equals("name") && !value.equals("")) {
                student.setName(value);
            } else if (tag.equals("sex") && !value.equals("")) {
                student.setSex(value);
            } else if (tag.equals("classes") && !value.equals("")) {
                student.setClasses(value);
            } else if (tag.equals("age") && !value.equals("")) {
                student.setAge(Integer.parseInt(value));
            } else if (tag.equals("school") && !value.equals("")) {
                student.setSchool(value);
            }
        }

    }

    public List<Student> getStudents() {
        return students;
    }

}
